package com.cennavi.minenavidemo.activity.offline;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.cennavi.minenavidemo.R;
import com.cennavi.minenavidemo.utils.Config;
import com.cennavi.minenavidemo.utils.DataStoresActivityJumpCityEvent;
import com.cennavi.minenavidemo.utils.ScreenUtil;
import com.cennavi.minenavidemo.widget.CommonTitleBar;
import com.cennavi.minenavidemo.widget.MultipleChoiceButton;
import com.cennavi.minenavidemo.widget.SelectItemDialog;
import com.cennavi.minenavidemo.widget.SettingItemView;
import com.minedata.minenavi.SDKInitializer;
import com.minedata.minenavi.mapdal.DataPreference;
import com.minedata.minenavi.mapdal.DataUpdateTask;
import com.minedata.minenavi.mapdal.Datastore;
import com.minedata.minenavi.mapdal.DatastoreItem;
import com.minedata.minenavi.mapdal.WmrObject;
import com.minedata.minenavi.mapdal.WorldManager;
import com.minedata.minenavi.navi.NaviSession;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static android.view.View.GONE;
import static android.view.View.INVISIBLE;
import static android.view.View.VISIBLE;

/**
 * 数据商店
 */
public class DataStoresActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "DataStoresActivity";
    private String appPath = Environment.getExternalStorageDirectory() + "/navicore/minedata/";

    /**
     * group下载图标的下载状态
     */
    private static class DataItemImageShowState {
        public static final int UNDOWNLOAD = 0;
        public static final int PAUSE = 1;
        public static final int DELETE = 2;
        public static final int FAILED = 3;
        public static final int WAITING = 4;
        public static final int UPDATING = 5;
    }

    private static class DataStoresShowType {
        /**
         * 已经下载的本地数据
         */
        public static final int LOCAL_DATA = 0;
        /**
         * 城市列表
         */
        public static final int CITY_LIST = 1;
        /**
         * 下载中
         */
        public static final int DOWNLOADING_LIST = 2;

    }


    private Datastore mDatastore;
    private DatastoreItem[] mDataStoreItems;
    private List<Boolean> mGroupProvinceItemIsHideIvStateLists = new ArrayList<>(); // 城市列表是否隐藏状态按键
    private List<Boolean> mGroupProvinceItemHasDownloaded = new ArrayList<>(); // 城市列表省item是否下载完毕
    private DatastoreItem mCurrentSelectDatastoreItem; // 当前选择的DatastoreItem
    private DataStoreAdapter mDataStoreAdapter;
    private SelectItemDialog mLocalItemSelectDialog;

    private String mSearchKeyWord;
    private ArrayList<DatastoreItem> mSearchLists = new ArrayList<>(); // 搜索结果的集合
    private HashMap<String, WmrObject> mProvinceCityMap = new HashMap<>(); // 保存省市集合的WmrObject 以name为Key

    private boolean isRefrePercent = true;
    private boolean isSoftKeyBoardShow;
    private long lastDownloadingProgressUpdateTime;
    /**
     * {@link DataStoresShowType}
     */
    private int mCurrentShowManager;

    /**
     * 键盘收起展开监听
     */
    private ExpandableListView expandLv;
    private MultipleChoiceButton mSwitchLoadManagerBt;
    private LinearLayout ll_downloadManageBottomBar, mSearchTitleContainer, mSettingViewContainer;
    private TextView ll_downloadAll, ll_pauseAll, ll_deleteAll;
    private TextView mTvNoSearchResult;

    private CommonTitleBar mTitleBar;

    private ImageView mIvClearText;
    private EditText mFindEdit;
    private RelativeLayout mSearchContainer;
    private SettingItemView mSettingOfflineMap, mSettingOfflineRoute, mSettingWifiAutoUpdate;
    private LinearLayout mMainContainer;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_stores);
        initView();
        initDataStore(-1);
        Datastore.retainLockDescriptions();
        initSettingView();
        initProvinceCityMap();
    }

    public void initView() {
        mMainContainer = (LinearLayout) findViewById(R.id.container);
        expandLv = (ExpandableListView) findViewById(R.id.expandLv);
        ll_downloadManageBottomBar = (LinearLayout) findViewById(R.id.ll_downloadManageBottomBar);
        ll_downloadAll = (TextView) findViewById(R.id.downloadAll);
        ll_pauseAll = (TextView) findViewById(R.id.pauseAll);
        ll_deleteAll = (TextView) findViewById(R.id.deleteAll);
        mFindEdit = (EditText) findViewById(R.id.find_edit);
        mTitleBar = (CommonTitleBar) findViewById(R.id.title_bar);

        mSearchTitleContainer = (LinearLayout) findViewById(R.id.search_title_container);
        mSettingViewContainer = (LinearLayout) findViewById(R.id.setting_view_container);
        mSettingOfflineMap = (SettingItemView) findViewById(R.id.setting_offline_map);
        mSettingOfflineRoute = (SettingItemView) findViewById(R.id.setting_offline_route);
        mSettingWifiAutoUpdate = (SettingItemView) findViewById(R.id.setting_wifi_auto_update);

        mSwitchLoadManagerBt = new MultipleChoiceButton(this);
        mTitleBar.setTitleName("设置");
        mTitleBar.setCustomTitleView(mSwitchLoadManagerBt, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT
                , getResources().getDimensionPixelSize(R.dimen.nz_px_64)));
        mTitleBar.setOnTitleBarItemClickListener(new CommonTitleBar.OnTitleBarItemClickListener() {
            @Override
            public void onLeftItemClick() {
                if (mSettingViewContainer.getVisibility() == VISIBLE) {
                    mSettingViewContainer.setVisibility(GONE);
                    mTitleBar.showCustomTitleContainerView();
                    mSwitchLoadManagerBt.setVisibility(VISIBLE);
                    mSearchTitleContainer.setVisibility(VISIBLE);
                    mTitleBar.setRightImageVisibility(VISIBLE);
                    return;
                }
                finish();
                overridePendingTransition(0, 0);
            }

            @Override
            public void onRightItemClick() {
                mSearchTitleContainer.setVisibility(GONE);
                mSwitchLoadManagerBt.setVisibility(GONE);
                mTitleBar.setRightImageVisibility(INVISIBLE);
                mTitleBar.showTitleName();
                mSettingViewContainer.setVisibility(View.VISIBLE);
            }
        });

        mSwitchLoadManagerBt.setOnChoiceListener(position -> {
            switch (position) {
                case DataStoresShowType.LOCAL_DATA:
                    mCurrentShowManager = position;
                    mFindEdit.setText("");
                    enableInputMethod(false);
                    loadCurrentDataStoresData(true);
                    break;
                case DataStoresShowType.CITY_LIST:
                    mCurrentShowManager = position;
                    mFindEdit.setText("");
                    enableInputMethod(false);
                    loadCurrentDataStoresData(true);
                    break;
                case DataStoresShowType.DOWNLOADING_LIST:
                    mCurrentShowManager = position;
                    mFindEdit.setText("");
                    enableInputMethod(false);
                    loadCurrentDataStoresData(true);
                    break;
            }
        });
        mSearchContainer = (RelativeLayout) findViewById(R.id.search_container);
        mTvNoSearchResult = (TextView) findViewById(R.id.tv_no_search_result);
        mIvClearText = (ImageView) findViewById(R.id.iv_clearText);
        mSwitchLoadManagerBt.post(new Runnable() {
            @Override
            public void run() {
                String[] sourceContent = {"本地数据", "城市列表", "下载管理"};
                mSwitchLoadManagerBt.setContent(sourceContent);
                mCurrentShowManager = DataStoresShowType.LOCAL_DATA;
                mSwitchLoadManagerBt.setChoice(mCurrentShowManager);
            }
        });

        ll_downloadAll.setOnClickListener(this);
        ll_pauseAll.setOnClickListener(this);
        ll_deleteAll.setOnClickListener(this);
        mIvClearText.setOnClickListener(this);
        initEdit();
    }

    private void initExpandListView() {
        if (mDataStoreAdapter != null) {
            return;
        }
        expandLv.setVisibility(View.VISIBLE);
        expandLv.setDividerHeight(1);
        expandLv.setGroupIndicator(null);
        expandLv.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState != AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    enableInputMethod(false);
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            }
        });
        mDataStoreAdapter = new DataStoreAdapter();
        expandLv.setAdapter(mDataStoreAdapter);
    }

    private void initEdit() {
        mFindEdit.setOnClickListener(v -> {
            if (mDataStoreAdapter != null) {
                mDataStoreAdapter.notifyDataSetInvalidated();
            }
        });
        mFindEdit.addTextChangedListener(mTextWatcher);
        mFindEdit.setCursorVisible(false);
    }

    public void enableInputMethod(boolean enable) {
        InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (enable) {
            //弹出键盘
            if (isSoftKeyBoardShow) {
                return;
            }
            mFindEdit.requestFocus();
            inputManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        } else {
            //隐藏键盘
            if (!isSoftKeyBoardShow) {
                return;
            }
            inputManager.hideSoftInputFromWindow(mFindEdit.getWindowToken(), 0);
        }
    }

    public void initDataStore(int version) {
        mDatastore = new Datastore(SDKInitializer.getAppPath());
        mDatastore.setServerVersion(version);
        mDatastore.setDataTypesRequired(Datastore.MapDataType.all ^ Datastore.MapDataType.jv);
        mDatastore.setNeedsRefresh();
        mDatastore.addEventHandler(mDataStoresHandler);
    }

    private void initSettingView() {
        //mSettingOfflineMap.rightLockEnableChecked(SettingV2.isMapPreferOffline());
        //mSettingOfflineRoute.rightLockEnableChecked(SettingV2.isRoutePreferOffline());
        //mSettingWifiAutoUpdate.rightLockEnableChecked(SettingV2.isWifiAutoDownload());

        mSettingOfflineMap.setOnRightLockingClick(() -> {
            boolean isEnableChecked = mSettingOfflineMap.rightIsEnableChecked();
            mSettingOfflineMap.rightLockEnableChecked(!isEnableChecked);
            //SettingV2.enableMapPreferOffline(!isEnableChecked);
            //MapPresenter.getInstance().getMineMap().setDataPreference(!isEnableChecked ? DataPreference.preferOffline : DataPreference.preferOnline);
        });

        mSettingOfflineRoute.setOnRightLockingClick(() -> {
            boolean isEnableChecked = mSettingOfflineRoute.rightIsEnableChecked();
            mSettingOfflineRoute.rightLockEnableChecked(!isEnableChecked);
            //SettingV2.enableRoutePreferOffline(!isEnableChecked);
            NaviSession.getInstance().setDataPreference(!isEnableChecked ? DataPreference.preferOffline : DataPreference.preferOnline);
        });

        mSettingWifiAutoUpdate.setOnRightLockingClick(() -> {
            boolean isEnableChecked = mSettingWifiAutoUpdate.rightIsEnableChecked();
            mSettingWifiAutoUpdate.rightLockEnableChecked(!isEnableChecked);
            //SettingV2.enableWifiAutoDownload(!isEnableChecked);
        });
    }

    /**
     * 初始化省市集合
     */
    private void initProvinceCityMap() {
        int rootId = WorldManager.getInstance().getRoot();
        if (rootId == WmrObject.INVALID_ID) {
            return;
        }
        WmrObject root = new WmrObject(rootId);
        WmrObject[] provinces = root.getChildrenWithVirtualNode(false);
        for (WmrObject province : provinces) {
            if (province.hasPed) {
                mProvinceCityMap.put(province.chsName, province);
            } else {
                WmrObject[] cities = province.getChildrenWithVirtualNode(false);
                for (WmrObject city : cities) {
                    mProvinceCityMap.put(city.chsName, city);
                }
            }
        }
    }

    public void loadCurrentDataStoresData(boolean isCollapseAllGroup) {
        if (TextUtils.isEmpty(mFindEdit.getText().toString())) {
            switch (mCurrentShowManager) {
                case DataStoresShowType.CITY_LIST:
                    loadCityDataList();
                    break;
                case DataStoresShowType.DOWNLOADING_LIST:
                    loadDownloadingDataList();
                    break;
                case DataStoresShowType.LOCAL_DATA:
                    loadLocalDataList();
                    break;
            }
        } else {
            mSearchLists.clear();
            mDatastore.filterNodes(mDatastoreNodeFilter);
        }
        if (mDataStoreAdapter != null) {
            mDataStoreAdapter.notifyDataSetChanged();
            if (isCollapseAllGroup) {
                collapseAllGroup();
            }
        }
    }

    public void loadCityDataList() {
        mCurrentShowManager = DataStoresShowType.CITY_LIST;
        mDataStoreItems = mDatastore.getRoot().getSubnodes();
        ll_downloadManageBottomBar.setVisibility(GONE);
        mTvNoSearchResult.setVisibility(GONE);
        expandLv.setVisibility(View.VISIBLE);
        mSearchContainer.setVisibility(View.VISIBLE);
    }

    public void loadDownloadingDataList() {
        mCurrentShowManager = DataStoresShowType.DOWNLOADING_LIST;
        ll_downloadManageBottomBar.setVisibility(View.VISIBLE);
        ll_downloadAll.setText("全部开始");
        mTvNoSearchResult.setVisibility(GONE);
        expandLv.setVisibility(View.VISIBLE);
        DataUpdateTask[] downloadTasks = mDatastore.getDownloadTaskList();
        DataUpdateTask[] filterDownloadTasks = null;
        int filterTaskNum = 0;
        for (DataUpdateTask dataUpdateTask : downloadTasks) {
            if (dataUpdateTask.state != DataUpdateTask.State.toBeRenamed) {
                filterTaskNum++;
            }
        }
        filterDownloadTasks = new DataUpdateTask[filterTaskNum];
        int insertIndex = 0;
        for (DataUpdateTask dataUpdateTask : downloadTasks) {
            if (dataUpdateTask.state != DataUpdateTask.State.toBeRenamed) {
                filterDownloadTasks[insertIndex] = dataUpdateTask;
                insertIndex++;
            }
        }

        mDataStoreItems = new DatastoreItem[filterDownloadTasks.length];
        for (int i = 0; i < filterDownloadTasks.length; i++) {
            DatastoreItem datastoreItem = mDatastore.getDatastoreItemById(filterDownloadTasks[i].id);
            mDataStoreItems[i] = datastoreItem;
        }

        List<Boolean> downloadingTaskPauseLists = new ArrayList<>();
        int whiteColor = Color.WHITE;
        int grayColor = getResources().getColor(R.color.data_stores_gray);
        if (mDataStoreItems.length != 0) {
            ll_deleteAll.setTextColor(whiteColor);
            ll_downloadAll.setTextColor(grayColor);
            ll_pauseAll.setTextColor(grayColor);
            for (DatastoreItem dataStoreItem : mDataStoreItems) {
                DataUpdateTask task = mDatastore.getDataUpdateTaskWithId(dataStoreItem.id);
                if (task.state == DataUpdateTask.State.paused) {
                    downloadingTaskPauseLists.add(true);
                    ll_downloadAll.setTextColor(whiteColor);
                } else {
                    downloadingTaskPauseLists.add(false);
                }
            }
        } else {
            ll_downloadAll.setTextColor(grayColor);
            ll_pauseAll.setTextColor(grayColor);
            ll_deleteAll.setTextColor(grayColor);
        }

        //更新暂停按钮的颜色，如果全部没有暂停的话，按钮白色，默认是灰色
        for (Boolean downloadingTaskPauseList : downloadingTaskPauseLists) {
            if (!downloadingTaskPauseList) {
                ll_pauseAll.setTextColor(whiteColor);
                break;
            }
        }
    }

    public void loadLocalDataList() {
        mCurrentShowManager = DataStoresShowType.LOCAL_DATA;
        ll_downloadManageBottomBar.setVisibility(View.VISIBLE);
        ll_downloadAll.setText("全部更新");
        mTvNoSearchResult.setVisibility(GONE);
        expandLv.setVisibility(View.VISIBLE);
        DatastoreItem[] downloadTasks = mDatastore.getRoot().getSubnodes();
        DatastoreItem[] localDataStroe = null;
        ArrayList<DatastoreItem> localItem = new ArrayList<>();

        for (DatastoreItem downloadTask : downloadTasks) {
            if (!downloadTask.hasSubnodes && (downloadTask.state == DatastoreItem.State.hasUpdate || downloadTask.state == DatastoreItem.State.upToDate)) {
                localItem.add(downloadTask);
                continue;
            }
            for (DatastoreItem item : downloadTask.getSubnodes()) {
                if (item.state == DatastoreItem.State.hasUpdate || item.state == DatastoreItem.State.upToDate) {
                    if (!localItem.contains(downloadTask)) {
                        localItem.add(downloadTask);
                    }
                }
            }
        }
        localDataStroe = new DatastoreItem[localItem.size()];

        for (int i = 0; i < localItem.size(); i++) {
            localDataStroe[i] = localItem.get(i);
        }

        int whiteColor = Color.WHITE;
        int grayColor = getResources().getColor(R.color.data_stores_gray);
        mDataStoreItems = localDataStroe;
        if (mDataStoreItems.length != 0) {
            ll_pauseAll.setTextColor(grayColor);
            ll_deleteAll.setTextColor(whiteColor);
            for (DatastoreItem dataStoreItem : mDataStoreItems) {
                if (dataStoreItem.hasSubnodes) {
                    for (DatastoreItem item : dataStoreItem.getSubnodes()) {
                        if (item.state == DatastoreItem.State.hasUpdate) {
                            ll_downloadAll.setTextColor(whiteColor);
                            break;
                        } else {
                            ll_downloadAll.setTextColor(grayColor);
                        }
                    }
                } else {
                    if (dataStoreItem.state == DatastoreItem.State.hasUpdate) {
                        ll_downloadAll.setTextColor(whiteColor);
                        break;
                    } else {
                        ll_downloadAll.setTextColor(grayColor);
                    }
                }
            }
        } else {
            ll_downloadAll.setTextColor(grayColor);
            ll_pauseAll.setTextColor(grayColor);
            ll_deleteAll.setTextColor(grayColor);
        }
    }

    public void refreshDataList() {
        lastDownloadingProgressUpdateTime = System.currentTimeMillis();
        loadCurrentDataStoresData(false);
    }

    public void collapseAllGroup() {
        for (int i = 0; i < mDataStoreItems.length; i++) {
            if (mDataStoreItems[i].hasSubnodes) {
                expandLv.collapseGroup(i);
            }
        }
    }

//    @Override
//    public void fitStatusBar(int statusBarHeight) {
//        mTitleBar.fitStatusBar(statusBarHeight);
//    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.downloadAll:
                if (mCurrentShowManager == DataStoresShowType.DOWNLOADING_LIST) {
                    for (DatastoreItem datastoreItem : mDataStoreItems) {
                        if (mDatastore.getDataUpdateTaskWithId(datastoreItem.id).state == DataUpdateTask.State.paused) {
                            mDatastore.resumeDataItem(datastoreItem.id);
                        }
                    }
                } else if (mCurrentShowManager == DataStoresShowType.LOCAL_DATA) {
                    for (DatastoreItem datastoreItem : mDataStoreItems) {
                        if (datastoreItem.hasSubnodes) {
                            for (DatastoreItem subItem : datastoreItem.getSubnodes()) {
                                if (subItem.state == DatastoreItem.State.hasUpdate) {
                                    mDatastore.createUpdateTaskForItem(subItem.id);
                                }
                            }
                        } else {
                            if (datastoreItem.state == DatastoreItem.State.hasUpdate) {
                                mDatastore.createUpdateTaskForItem(datastoreItem.id);
                            }
                        }
                    }
                }
                break;
            case R.id.pauseAll:
                if (mCurrentShowManager == DataStoresShowType.DOWNLOADING_LIST) {
                    for (DatastoreItem datastoreItem : mDataStoreItems) {
                        mDatastore.pauseDataItem(datastoreItem.id);
                    }
                } else if (mCurrentShowManager == DataStoresShowType.LOCAL_DATA) {
                    for (DatastoreItem datastoreItem : mDataStoreItems) {
                        if (datastoreItem.hasSubnodes) {
                            for (DatastoreItem subItem : datastoreItem.getSubnodes()) {
                                mDatastore.pauseDataItem(subItem.id);
                            }
                        } else {
                            mDatastore.pauseDataItem(datastoreItem.id);
                        }
                    }
                }

                break;
            case R.id.deleteAll:
                if (mCurrentShowManager == DataStoresShowType.DOWNLOADING_LIST) {
                    for (DatastoreItem datastoreItem : mDataStoreItems) {
                        mDatastore.pauseDataItem(datastoreItem.id);
                        mDatastore.cancelDataItem(datastoreItem.id);
                    }
                } else if (mCurrentShowManager == DataStoresShowType.LOCAL_DATA) {
                    for (DatastoreItem datastoreItem : mDataStoreItems) {
                        if (datastoreItem.hasSubnodes) {
                            for (DatastoreItem subItem : datastoreItem.getSubnodes()) {
                                mDatastore.deleteDataItem(subItem.id);
                            }
                        } else {
                            mDatastore.deleteDataItem(datastoreItem.id);
                        }
                    }
                }
                break;
            case R.id.iv_clearText:
                mFindEdit.setText("");
                if (mDataStoreAdapter != null) {
                    mDataStoreAdapter.notifyDataSetInvalidated();
                }
                collapseAllGroup();
                break;
        }
    }

    private class DataStoreAdapter extends BaseExpandableListAdapter {

        /**
         * 得到分析过的子节点
         */
        private DatastoreItem[] getAnalyzedSubnodes(DatastoreItem[] subDataStoreItem) {
            if (mCurrentShowManager == DataStoresShowType.CITY_LIST) {
                return subDataStoreItem;
            } else {
                DatastoreItem[] subDataStore = null;
                ArrayList<DatastoreItem> subItems = new ArrayList<>();

                for (DatastoreItem item : subDataStoreItem) {
                    if (item.state == DatastoreItem.State.hasUpdate || item.state == DatastoreItem.State.upToDate) {
                        subItems.add(item);
                    }
                }
                subDataStore = new DatastoreItem[subItems.size()];

                for (int i = 0; i < subItems.size(); i++) {
                    subDataStore[i] = subItems.get(i);
                }
                return subDataStore;
            }
        }

        @Override
        public int getGroupCount() {
            return mDataStoreItems.length;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            if (mDataStoreItems.length == 0) {
                return 0;
            } else if (mCurrentShowManager == DataStoresShowType.LOCAL_DATA) {
                return getAnalyzedSubnodes(mDataStoreItems[groupPosition].getSubnodes()).length;
            } else if (mCurrentShowManager == DataStoresShowType.CITY_LIST) {
                return mDataStoreItems[groupPosition].getSubnodes().length;
            } else {
                return 0;
            }
        }

        @Override
        public Object getGroup(int groupPosition) {
            return mDataStoreItems[groupPosition];
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return mDataStoreItems[groupPosition].getSubnodes()[childPosition];
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public View getGroupView(final int groupPosition, final boolean isExpanded, View convertView, ViewGroup parent) {
            final DataStoreItemHolder groupItemHolder;
            if (convertView == null) {
                convertView = View.inflate(DataStoresActivity.this, R.layout.datastore_item, null);
                convertView.setBackgroundColor(ContextCompat.getColor(DataStoresActivity.this, R.color.white));
                groupItemHolder = new DataStoreItemHolder(convertView);
                convertView.setTag(groupItemHolder);
            } else {
                groupItemHolder = (DataStoreItemHolder) convertView.getTag();
            }

            final DatastoreItem datastoreItem = mDataStoreItems[groupPosition];
            final DataUpdateTask dataUpdateTask = mDatastore.getDataUpdateTaskWithId(datastoreItem.id);

            int hasSubnodesLocalSize = 0;
            int nothasSubnodesLocalSize = datastoreItem.localDataSize / 1024 / 1024;
            int incrementalSize = datastoreItem.incrementUpdateDataSize / 1024 / 1024;
            int fullSize = datastoreItem.fullUpdateDataSize / 1024 / 1024;

            if (mCurrentShowManager == DataStoresShowType.LOCAL_DATA && datastoreItem.hasSubnodes) {
                for (DatastoreItem item : datastoreItem.getSubnodes()) {
                    hasSubnodesLocalSize += item.localDataSize;
                }
            }
            hasSubnodesLocalSize = hasSubnodesLocalSize / 1024 / 1024;

            groupItemHolder.tv_name.setText(datastoreItem.name);
            groupItemHolder.iv_state.setVisibility(View.VISIBLE);
            if (mCurrentShowManager == DataStoresShowType.CITY_LIST) {
                groupItemHolder.iv_download_point_state.setVisibility(View.VISIBLE);
            } else {
                groupItemHolder.iv_download_point_state.setVisibility(INVISIBLE);
            }

            if (mCurrentShowManager == DataStoresShowType.LOCAL_DATA) {
                groupItemHolder.download_progress.setVisibility(GONE);
            } else if (mCurrentShowManager == DataStoresShowType.CITY_LIST) {
                if (dataUpdateTask != null
                        && (dataUpdateTask.state == DataUpdateTask.State.downloading || dataUpdateTask.state == DataUpdateTask.State.paused)
                        && !datastoreItem.hasSubnodes) {
                    groupItemHolder.download_progress.setVisibility(View.VISIBLE);
                } else {
                    groupItemHolder.download_progress.setVisibility(GONE);
                }
            } else {
                groupItemHolder.download_progress.setVisibility(View.VISIBLE);
            }
            mGroupProvinceItemIsHideIvStateLists.clear();
            mGroupProvinceItemHasDownloaded.clear();

            if (datastoreItem.hasSubnodes) {//表示此条目是省，如辽宁省
                groupItemHolder.fold_state_container.setVisibility(View.VISIBLE);
                groupItemHolder.tv_sate.setVisibility(GONE);
                if (mCurrentShowManager == DataStoresShowType.LOCAL_DATA) {
                    groupItemHolder.tv_downloadSize.setText(hasSubnodesLocalSize + "M");
                } else {
                    groupItemHolder.tv_downloadSize.setText(fullSize == 0 ? "" : fullSize + "M");
                }
                groupItemHolder.tv_download_progress.setVisibility(GONE);


                if (mCurrentShowManager == DataStoresShowType.CITY_LIST) {
                    //为了采集当前省所有子节点是否都有下载任务或者已经下载好了
                    for (DatastoreItem item : datastoreItem.getSubnodes()) {
                        DataUpdateTask subTask = mDatastore.getDataUpdateTaskWithId(item.id);
                        if (subTask != null) {//该子节点有下载任务
                            mGroupProvinceItemHasDownloaded.add(false);
                            mGroupProvinceItemIsHideIvStateLists.add(true);
                        } else {//改子节点无下载任务或已经下载完成
                            mGroupProvinceItemIsHideIvStateLists.add(false);
                            if (item.state == DatastoreItem.State.upToDate) {
                                mGroupProvinceItemHasDownloaded.add(true);
                            } else if (item.state == DatastoreItem.State.hasUpdate) {
                                mGroupProvinceItemHasDownloaded.add(true);
                            } else {
                                mGroupProvinceItemHasDownloaded.add(false);
                            }
                        }
                    }

                    //为了更新状态点和图片
                    for (Boolean aBoolean : mGroupProvinceItemHasDownloaded) {
                        if (aBoolean) {
                            groupItemHolder.iv_download_point_state.setImageResource(R.drawable.green_point);
                            groupItemHolder.iv_state.setImageResource(R.drawable.delete);
                            groupItemHolder.iv_state.setTag(DataItemImageShowState.DELETE);
                            groupItemHolder.iv_state.setVisibility(INVISIBLE);
                        } else {
                            groupItemHolder.iv_state.setImageResource(R.drawable.undownloaded);
                            groupItemHolder.iv_state.setTag(DataItemImageShowState.UNDOWNLOAD);
                            groupItemHolder.iv_state.setVisibility(VISIBLE);
                            groupItemHolder.iv_download_point_state.setImageResource(R.drawable.gray_point);
                            break;
                        }
                    }

                    // 判断该省内部的所有城市是不是都有下载任务，如果有，就隐藏该省的下载图标
                    for (Boolean isHide : mGroupProvinceItemIsHideIvStateLists) {
                        if (isHide) {
                            groupItemHolder.iv_state.setVisibility(INVISIBLE);
                        } else {
                            groupItemHolder.iv_state.setVisibility(View.VISIBLE);
                            break;
                        }
                    }

                    //如果该省的下载图标是删除，说明全部子节点都下载完成
                    if ((int) groupItemHolder.iv_state.getTag() == DataItemImageShowState.DELETE) {
                        groupItemHolder.iv_state.setVisibility(View.INVISIBLE);
                    }

                } else {
                    groupItemHolder.iv_state.setVisibility(INVISIBLE);
                }

                if (!isExpanded) {
                    groupItemHolder.iv_fold_state.setImageResource(R.drawable.unfold);
                } else {
                    groupItemHolder.iv_fold_state.setImageResource(R.drawable.fold);
                }
            } else {// 北京市或者下载中的条目
                groupItemHolder.fold_state_container.setVisibility(View.GONE);
                groupItemHolder.iv_state.setVisibility(View.VISIBLE);
                int downlaodSize = 0;
                if (incrementalSize <= fullSize) {
                    downlaodSize = incrementalSize;
                } else {
                    downlaodSize = fullSize;
                }
                if (mCurrentShowManager == DataStoresShowType.LOCAL_DATA) {
                    groupItemHolder.tv_downloadSize.setText(nothasSubnodesLocalSize + "M");
                } else {
                    groupItemHolder.tv_downloadSize.setText((downlaodSize == 0 ? nothasSubnodesLocalSize : downlaodSize) + "M");
                }
                int blueTextColor = Color.parseColor("#3c78ff");
                int redTextColor = Color.RED;

                if (dataUpdateTask != null) { //该条目有下载任务，暂停或者下载中或者其他状态等
                    groupItemHolder.iv_state.setImageResource(R.drawable.download_waiting);
                    groupItemHolder.iv_state.setTag(DataItemImageShowState.WAITING);
                    groupItemHolder.tv_sate.setTextColor(blueTextColor);
                    groupItemHolder.iv_download_point_state.setImageResource(R.drawable.download_point);
                    if (mCurrentShowManager == DataStoresShowType.CITY_LIST) {
                        groupItemHolder.tv_download_progress.setVisibility(GONE);
                        groupItemHolder.tv_sate.setVisibility(GONE);
                    } else {
                        groupItemHolder.tv_download_progress.setVisibility(View.VISIBLE);
                        groupItemHolder.tv_sate.setVisibility(View.VISIBLE);
                    }
                    if (dataUpdateTask.state == DataUpdateTask.State.downloading) {
                        groupItemHolder.tv_sate.setText("正在下载");
                        int progress = (int) (dataUpdateTask.downloadProgress * 100);
                        groupItemHolder.tv_download_progress.setText(progress + "%");
                        groupItemHolder.download_progress.setProgress(progress);
                    } else if (dataUpdateTask.state == DataUpdateTask.State.paused) {
                        groupItemHolder.tv_sate.setTextColor(redTextColor);
                        groupItemHolder.tv_sate.setText("已暂停");
                        groupItemHolder.tv_download_progress.setText("");
                        groupItemHolder.iv_state.setImageResource(R.drawable.download_pause);
                        groupItemHolder.iv_download_point_state.setImageResource(R.drawable.gray_point);
                        groupItemHolder.iv_state.setTag(DataItemImageShowState.PAUSE);
                        if (dataUpdateTask.downloadProgress != 1) {
                            groupItemHolder.download_progress.setProgress((int) (dataUpdateTask.downloadProgress * 100));
                        } else {
                            groupItemHolder.download_progress.setProgress((int) (dataUpdateTask.installProgress * 100));
                        }
                    } else if (dataUpdateTask.state == DataUpdateTask.State.failed) {
                        groupItemHolder.tv_sate.setTextColor(redTextColor);
                        groupItemHolder.tv_sate.setText("下载失败");
                        groupItemHolder.tv_download_progress.setText("下载失败");
                        groupItemHolder.iv_state.setImageResource(R.drawable.download_failed);
                        groupItemHolder.iv_state.setTag(DataItemImageShowState.FAILED);
                        groupItemHolder.iv_download_point_state.setImageResource(R.drawable.gray_point);
                    } else if (dataUpdateTask.state == DataUpdateTask.State.waitInstall) {
                        groupItemHolder.tv_sate.setText("等待安装");
                        groupItemHolder.tv_download_progress.setText("等待安装");
                    } else if (dataUpdateTask.state == DataUpdateTask.State.installing) {
                        groupItemHolder.tv_sate.setText("正在安装");
                        int progress = (int) (dataUpdateTask.installProgress * 100);
                        groupItemHolder.tv_download_progress.setText(progress + "%");
                        groupItemHolder.download_progress.setProgress(progress);
                    }
					/*else if (dataUpdateTask.state == DataUpdateTask.State.beforeDownloadingPaused) {
						dataStoreItemHolder.tv_sate.setText("暂停中");
					}*/
                    else if (dataUpdateTask.state == DataUpdateTask.State.toBeRenamed) {
                        groupItemHolder.tv_sate.setText("等待数据空闲时安装");
                        groupItemHolder.tv_download_progress.setText("");
                        groupItemHolder.tv_downloadSize.setText("");
                        groupItemHolder.iv_state.setVisibility(INVISIBLE);
                    } else if (dataUpdateTask.state == DataUpdateTask.State.waitDownload) {
                        groupItemHolder.tv_download_progress.setText("等待下载");
                        groupItemHolder.tv_sate.setText("等待下载");
                        groupItemHolder.iv_state.setImageResource(R.drawable.download_waiting);
                        groupItemHolder.iv_state.setTag(DataItemImageShowState.WAITING);
                    } else if (dataUpdateTask.state == DataUpdateTask.State.toBeDeleted) {
                        groupItemHolder.tv_sate.setText("等待数据空闲时删除");
                        groupItemHolder.tv_downloadSize.setText("");
                        groupItemHolder.tv_download_progress.setText("");
                        groupItemHolder.iv_state.setVisibility(INVISIBLE);
                    }
                } else { // 该条目没有下载任务，如已经下载完成或者没有下载等
                    groupItemHolder.tv_download_progress.setVisibility(GONE);
                    if (mCurrentShowManager == DataStoresShowType.CITY_LIST) {
                        groupItemHolder.tv_sate.setVisibility(GONE);
                    } else {
                        groupItemHolder.tv_sate.setVisibility(View.VISIBLE);
                    }
                    groupItemHolder.tv_sate.setTextColor(blueTextColor);
                    if (datastoreItem.state == DatastoreItem.State.notDownloaded) {
                        groupItemHolder.tv_sate.setText("未下载");
                        groupItemHolder.iv_state.setImageResource(R.drawable.undownloaded);
                        groupItemHolder.iv_state.setTag(DataItemImageShowState.UNDOWNLOAD);
                        groupItemHolder.iv_download_point_state.setImageResource(R.drawable.gray_point);
                    } else if (datastoreItem.state == DatastoreItem.State.hasUpdate) {
                        groupItemHolder.tv_sate.setText("可更新");
                        groupItemHolder.iv_state.setImageResource(R.drawable.download_update);
                        groupItemHolder.iv_state.setTag(DataItemImageShowState.UPDATING);
                        groupItemHolder.iv_download_point_state.setImageResource(R.drawable.gray_point);
                    } else if (datastoreItem.state == DatastoreItem.State.upToDate) {
                        groupItemHolder.tv_sate.setText("");
                        groupItemHolder.iv_state.setImageResource(R.drawable.delete);
                        groupItemHolder.iv_state.setTag(DataItemImageShowState.DELETE);
                        groupItemHolder.iv_state.setVisibility(INVISIBLE);
                        groupItemHolder.iv_download_point_state.setImageResource(R.drawable.green_point);
                    }
                }
            }

            if (!datastoreItem.hasSubnodes) {
                convertView.setOnClickListener(v -> {
                    enableInputMethod(false);
                    if (mCurrentShowManager == DataStoresShowType.CITY_LIST || mCurrentShowManager == DataStoresShowType.DOWNLOADING_LIST) {
                        downloadOrPauseItem(datastoreItem);
                    } else {
                        showLocalSelectDialog(datastoreItem);
                    }
                });
            } else {
                if (mCurrentShowManager == DataStoresShowType.LOCAL_DATA) {
                    convertView.setOnClickListener(v -> showLocalSelectDialog(datastoreItem));
                } else {
                    convertView.setClickable(false);
                }
            }

            groupItemHolder.fold_state_container.setOnClickListener(v -> {
                if (expandLv.isGroupExpanded(groupPosition)) {
                    expandLv.collapseGroup(groupPosition);
                } else {
                    expandLv.expandGroup(groupPosition);
                }
            });

            groupItemHolder.iv_state.setOnClickListener(v -> {
                enableInputMethod(false);
                downloadOrPauseItem(datastoreItem);
            });
            return convertView;
        }

        @Override
        public View getChildView(final int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            final DataStoreItemHolder childItemHolder;
            if (convertView == null) {
                convertView = View.inflate(DataStoresActivity.this, R.layout.datastore_item, null);
                convertView.setBackgroundColor(Color.parseColor("#f3f5f7"));
                childItemHolder = new DataStoreItemHolder(convertView);
                convertView.setTag(childItemHolder);
            } else {
                childItemHolder = (DataStoreItemHolder) convertView.getTag();
            }

            final DatastoreItem datastoreItem = getAnalyzedSubnodes(mDataStoreItems[groupPosition].getSubnodes())[childPosition];
            final DataUpdateTask dataUpdateTask = mDatastore.getDataUpdateTaskWithId(datastoreItem.id);

            int localSize = datastoreItem.localDataSize / 1024 / 1024;
            int incrementalSize = datastoreItem.incrementUpdateDataSize / 1024 / 1024;
            int fullSize = datastoreItem.fullUpdateDataSize / 1024 / 1024;

            childItemHolder.tv_name.setText(datastoreItem.name);
            childItemHolder.fold_state_container.setVisibility(GONE);
            if (dataUpdateTask != null
                    && (dataUpdateTask.state == DataUpdateTask.State.downloading || dataUpdateTask.state == DataUpdateTask.State.paused)) {
                childItemHolder.download_progress.setVisibility(View.VISIBLE);
            } else {
                childItemHolder.download_progress.setVisibility(GONE);
            }
            childItemHolder.iv_state.setVisibility(View.VISIBLE);
            childItemHolder.tv_download_progress.setVisibility(GONE);

            if (mCurrentShowManager == DataStoresShowType.CITY_LIST) {
                childItemHolder.iv_download_point_state.setVisibility(View.VISIBLE);
                childItemHolder.tv_sate.setVisibility(View.GONE);
            } else {
                childItemHolder.iv_download_point_state.setVisibility(INVISIBLE);
                childItemHolder.tv_sate.setVisibility(View.VISIBLE);
            }

            int downlaodSize = 0;
            if (incrementalSize <= fullSize) {
                downlaodSize = incrementalSize;
            } else {
                downlaodSize = fullSize;
            }
            if (mCurrentShowManager == DataStoresShowType.CITY_LIST) {
                childItemHolder.tv_downloadSize.setText((downlaodSize == 0 ? localSize : downlaodSize) + "M");
            } else if (mCurrentShowManager == DataStoresShowType.LOCAL_DATA) {
                childItemHolder.tv_downloadSize.setText(localSize + "M");
            }

            int blueTextColor = Color.parseColor("#3c78ff");
            int redTextColor = Color.RED;

            if (dataUpdateTask != null) {
                childItemHolder.iv_state.setImageResource(R.drawable.download_waiting);
                childItemHolder.tv_sate.setTextColor(blueTextColor);
                childItemHolder.iv_download_point_state.setImageResource(R.drawable.download_point);
                if (dataUpdateTask.state == DataUpdateTask.State.downloading) {
                    childItemHolder.tv_sate.setText("正在下载");
                    int progress = (int) (dataUpdateTask.downloadProgress * 100);
                    childItemHolder.tv_download_progress.setText(progress + "%");
                    childItemHolder.download_progress.setProgress(progress);
                } else if (dataUpdateTask.state == DataUpdateTask.State.paused) {
                    childItemHolder.tv_sate.setTextColor(redTextColor);
                    childItemHolder.tv_sate.setText("已暂停");
                    childItemHolder.iv_state.setImageResource(R.drawable.download_pause);
                    if (dataUpdateTask.downloadProgress != 1) {
                        childItemHolder.download_progress.setProgress((int) (dataUpdateTask.downloadProgress * 100));
                    } else {
                        childItemHolder.download_progress.setProgress((int) (dataUpdateTask.installProgress * 100));
                    }
                } else if (dataUpdateTask.state == DataUpdateTask.State.failed) {
                    childItemHolder.tv_sate.setTextColor(redTextColor);
                    childItemHolder.tv_sate.setText("下载失败");
                } else if (dataUpdateTask.state == DataUpdateTask.State.waitInstall) {
                    childItemHolder.tv_sate.setText("等待安装");
                } else if (dataUpdateTask.state == DataUpdateTask.State.installing) {
                    childItemHolder.tv_sate.setText("正在安装");
                    int progress = (int) (dataUpdateTask.installProgress * 100);
                    childItemHolder.tv_download_progress.setText(progress + "%");
                    childItemHolder.download_progress.setProgress(progress);
                }
				/*else if (dataUpdateTask.state == DataUpdateTask.State.beforeDownloadingPaused) {
					itemHolder.tv_sate.setText("暂停中");
				} */
                else if (dataUpdateTask.state == DataUpdateTask.State.toBeRenamed) {
                    childItemHolder.tv_sate.setText("等待数据空闲时安装");
                    childItemHolder.tv_downloadSize.setText("");
                    childItemHolder.iv_state.setVisibility(INVISIBLE);
                } else if (dataUpdateTask.state == DataUpdateTask.State.waitDownload) {
                    childItemHolder.tv_sate.setText("等待下载");
                    childItemHolder.iv_state.setImageResource(R.drawable.download_waiting);
                } else if (dataUpdateTask.state == DataUpdateTask.State.toBeDeleted) {
                    childItemHolder.tv_sate.setText("等待数据空闲时删除");
                    childItemHolder.tv_downloadSize.setText("");
                    childItemHolder.iv_state.setVisibility(INVISIBLE);
                }
            } else {
                childItemHolder.tv_sate.setTextColor(blueTextColor);
                if (datastoreItem.state == DatastoreItem.State.notDownloaded) {
                    childItemHolder.tv_sate.setText("未下载");
                    childItemHolder.iv_state.setImageResource(R.drawable.undownloaded);
                    childItemHolder.iv_download_point_state.setImageResource(R.drawable.gray_point);
                } else if (datastoreItem.state == DatastoreItem.State.hasUpdate) {
                    childItemHolder.tv_sate.setText("可更新");
                    childItemHolder.iv_state.setImageResource(R.drawable.download_update);
                    childItemHolder.iv_download_point_state.setImageResource(R.drawable.gray_point);
                } else if (datastoreItem.state == DatastoreItem.State.upToDate) {
                    childItemHolder.tv_sate.setText("");
                    childItemHolder.iv_state.setImageResource(R.drawable.delete);
                    childItemHolder.iv_state.setVisibility(INVISIBLE);
                    childItemHolder.iv_download_point_state.setImageResource(R.drawable.green_point);
                }
            }

            convertView.setOnClickListener(v -> {
                enableInputMethod(false);
                if (mCurrentShowManager == DataStoresShowType.LOCAL_DATA) {
                    showLocalSelectDialog(datastoreItem);
                } else {
                    downloadOrPauseItem(datastoreItem);
                }
            });
            return convertView;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
    }

    private void showLocalSelectDialog(DatastoreItem item) {
        mCurrentSelectDatastoreItem = item;
        mLocalItemSelectDialog = new SelectItemDialog(DataStoresActivity.this);
        mLocalItemSelectDialog.initDataStoreCheckDownloadDataSelectItemDialog(mLocalItemClickDialogListener, item);
        mLocalItemSelectDialog.showAtLocation(mMainContainer, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL
                , 0, ScreenUtil.getInstance().getNavigationBarHeight());
    }

    /**
     * 下载数据或暂停数据商店的item
     *
     * @param datastoreItem 下载的item
     */
    private void downloadOrPauseItem(DatastoreItem datastoreItem) {
        if (!isBaseData(datastoreItem)) {
            downloadBaseData();
        }
        DataUpdateTask dataUpdateTask = mDatastore.getDataUpdateTaskWithId(datastoreItem.id);
        if (!datastoreItem.hasSubnodes) {
            if (dataUpdateTask == null) { // 没有下载或者已经下载完成.
                if (datastoreItem.state == DatastoreItem.State.hasUpdate || datastoreItem.state == DatastoreItem.State.notDownloaded) {
                    mDatastore.createUpdateTaskForItem(datastoreItem.id);
                }
            } else {
                if (dataUpdateTask.state == DataUpdateTask.State.downloading) {
                    mDatastore.pauseDataItem(datastoreItem.id);
                } else if (dataUpdateTask.state == DataUpdateTask.State.paused) {
                    mDatastore.resumeDataItem(datastoreItem.id);
                } else if (dataUpdateTask.state == DataUpdateTask.State.failed) {
                    mDatastore.cancelDataItem(datastoreItem.id);
                    mDatastore.createUpdateTaskForItem(datastoreItem.id);
                } else {
                    loadCurrentDataStoresData(false);
                }
            }
        } else {
            //点击下载一个省的所有数据
            for (DatastoreItem item : datastoreItem.getSubnodes()) {
                DataUpdateTask subItemTask = mDatastore.getDataUpdateTaskWithId(item.id);
                if (subItemTask != null) {
                    if (subItemTask.state == DataUpdateTask.State.paused) {
                        mDatastore.resumeDataItem(item.id);
                    } else if (subItemTask.state != DataUpdateTask.State.none) {
                        mDatastore.createUpdateTaskForItem(item.id);
                    }
                } else {
                    if (item.state == DatastoreItem.State.hasUpdate || item.state == DatastoreItem.State.notDownloaded) {
                        mDatastore.createUpdateTaskForItem(item.id);
                    }
                }
            }
        }
    }

    private boolean isBaseData(DatastoreItem item) {
        return item.name.equals("基础数据");
    }

    private void downloadBaseData() {
        for (DatastoreItem dataStoreItem : mDataStoreItems) {
            if (isBaseData(dataStoreItem)) {
                DataUpdateTask task = mDatastore.getDataUpdateTaskWithId(dataStoreItem.id);
                if (task == null) {
                    if ((dataStoreItem.state == DatastoreItem.State.notDownloaded
                            || dataStoreItem.state == DatastoreItem.State.hasUpdate)) {
                        mDatastore.createUpdateTaskForItem(dataStoreItem.id);
                    }
                } else {
                    if (task.state == DataUpdateTask.State.paused) {
                        mDatastore.resumeDataItem(dataStoreItem.id);
                    } else if (task.state == DataUpdateTask.State.failed) {
                        mDatastore.createUpdateTaskForItem(dataStoreItem.id);
                    }
                }
                break;
            }
        }
    }

    private static class DataStoreItemHolder {
        public TextView tv_name, tv_downloadSize, tv_sate, tv_download_progress;
        public ProgressBar download_progress;
        public ImageView iv_state, iv_fold_state, iv_download_point_state;
        public RelativeLayout fold_state_container;

        public DataStoreItemHolder(View view) {
            this.tv_name = (TextView) view.findViewById(R.id.tv_name);
            this.tv_downloadSize = (TextView) view.findViewById(R.id.tv_downloadSize);
            this.tv_sate = (TextView) view.findViewById(R.id.tv_sate);
            this.download_progress = (ProgressBar) view.findViewById(R.id.download_progress);
            this.iv_state = (ImageView) view.findViewById(R.id.iv_state);
            this.iv_download_point_state = (ImageView) view.findViewById(R.id.iv_download_point_state);
            this.iv_fold_state = (ImageView) view.findViewById(R.id.iv_fold_state);
            this.fold_state_container = (RelativeLayout) view.findViewById(R.id.fold_state_container);
            this.tv_download_progress = (TextView) view.findViewById(R.id.tv_download_progress);
        }
    }

    /**
     * 当前的数据的子节点是否都被删除
     */
    private boolean isHasSubNodeNotDelete(DatastoreItem datastoreItem) {
        if (!datastoreItem.hasSubnodes) {
            return false;
        }
        for (DatastoreItem item : datastoreItem.getSubnodes()) {
            if (item.state == DatastoreItem.State.hasUpdate || item.state == DatastoreItem.State.upToDate) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mDatastore.release();
    }

    @Override
    protected void onStart() {
        super.onStart();
        isRefrePercent = true;
    }

    @Override
    protected void onStop() {
        super.onStop();
        isRefrePercent = false;
    }

    @Override
    public void onBackPressed() {
        if (mLocalItemSelectDialog != null && mLocalItemSelectDialog.isShowing()) {
            mLocalItemSelectDialog.dismiss();
            return;
        }

        if (mSettingViewContainer.getVisibility() == VISIBLE) {
            mSettingViewContainer.setVisibility(GONE);
            mTitleBar.showCustomTitleContainerView();
            mSearchTitleContainer.setVisibility(VISIBLE);
            mSwitchLoadManagerBt.setVisibility(VISIBLE);
            mTitleBar.setRightImageVisibility(VISIBLE);
            return;
        }
        finish();
        overridePendingTransition(0, 0);
    }

    private View.OnClickListener mLocalItemClickDialogListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.check_map:
                    if (!mProvinceCityMap.isEmpty()) {
                        EventBus.getDefault().post(new DataStoresActivityJumpCityEvent(mProvinceCityMap.get(mCurrentSelectDatastoreItem.name)));
                        mLocalItemSelectDialog.dismiss();
                        finish();
                        overridePendingTransition(0, 0);
                    } else {
                        Toast.makeText(DataStoresActivity.this, "暂时无法查看", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.delete:
                    if (mCurrentSelectDatastoreItem.hasSubnodes) {
                        for (DatastoreItem item : mCurrentSelectDatastoreItem.getSubnodes()) {
                            if (item.state != DatastoreItem.State.notDownloaded) {
                                mDatastore.deleteDataItem(item.id);
                            }
                        }
                    } else {
                        mDatastore.deleteDataItem(mCurrentSelectDatastoreItem.id);
                    }
                    mLocalItemSelectDialog.dismiss();
                    break;
                case R.id.cancel:
                    mLocalItemSelectDialog.dismiss();
                    break;
            }
        }
    };

    private Datastore.DatastoreNodeFilter mDatastoreNodeFilter = new Datastore.DatastoreNodeFilter() {
        @Override
        public boolean onDatastoreMatchDataNodeOnly() {
            if (mCurrentShowManager == DataStoresShowType.CITY_LIST) {
                return false;
            } else if (mCurrentShowManager == DataStoresShowType.LOCAL_DATA) {
                return false;
            } else {
                return true;
            }
        }

        @Override
        public boolean onDatastoreFlattenNodes() {
            if (mCurrentShowManager == DataStoresShowType.CITY_LIST) {
                return false;
            } else if (mCurrentShowManager == DataStoresShowType.LOCAL_DATA) {
                return true;
            } else {
                return true;
            }
        }

        @Override
        public boolean onDatastoreShouldKeepItem(DatastoreItem datastoreItem) {
            if (mCurrentShowManager == DataStoresShowType.CITY_LIST) {
                if (datastoreItem.matchesWithKeyword(mSearchKeyWord)) {
                    mSearchLists.add(datastoreItem);
                }
            } else if (mCurrentShowManager == DataStoresShowType.LOCAL_DATA) {
                if (datastoreItem.matchesWithKeyword(mSearchKeyWord) && (datastoreItem.state == DatastoreItem.State.upToDate || datastoreItem.state == DatastoreItem.State.hasUpdate)) {
                    mSearchLists.add(datastoreItem);
                }
            } else {
                if (datastoreItem.matchesWithKeyword(mSearchKeyWord)) {
                    if (mDatastore.getDataUpdateTaskWithId(datastoreItem.id) != null) {
                        mSearchLists.add(datastoreItem);
                    }
                }
            }
            mDataStoreItems = mSearchLists.toArray(new DatastoreItem[mSearchLists.size()]);
            return false;
        }
    };

    TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String searchKeyWord = s.toString();
            mSearchKeyWord = searchKeyWord;
            mSearchLists.clear();
            if (!TextUtils.isEmpty(searchKeyWord)) {
                mDatastore.filterNodes(mDatastoreNodeFilter);

                mIvClearText.setVisibility(View.VISIBLE);
                if (mDataStoreItems.length == 0) {
                    mTvNoSearchResult.setVisibility(View.VISIBLE);
                    expandLv.setVisibility(View.GONE);
                } else {
                    mTvNoSearchResult.setVisibility(GONE);
                    expandLv.setVisibility(View.VISIBLE);
                    if (mDataStoreAdapter != null) {
                        mDataStoreAdapter.notifyDataSetChanged();
                    }
                    collapseAllGroup();
                }
            } else {
                mIvClearText.setVisibility(View.GONE);
                loadCurrentDataStoresData(true);
            }
        }
    };

    Datastore.EventHandler mDataStoresHandler = new Datastore.EventHandler() {
        @Override
        public void onDatastoreRefreshed() {
            loadCurrentDataStoresData(true);
            initExpandListView();
        }

        @Override
        public void onDatastoreRefreshedNoNetwork() {
        }

        @Override
        public void onDatastoreRefreshCanceled() {
        }

        @Override
        public void onDatastoreRefreshFailed() {
        }

        @Override
        public void onDatastoreDataItemQueryFileListSucceeded(String id) {
        }

        @Override
        public void onDatastoreDataItemQueryFileListFailed(String id, int errorCode) {
        }

        @Override
        public void onDatastoreDownloadingDataItemBegan(String id) {
        }

        @Override
        public void onDatastoreDownloadingDataItemProgressUpdated(String id, float percent) {
            if (isRefrePercent) {
                //0.5s刷新一次
                if (System.currentTimeMillis() - lastDownloadingProgressUpdateTime > 500) {
                    lastDownloadingProgressUpdateTime = System.currentTimeMillis();
                    expandLv.collapseGroup(0);
                    expandLv.expandGroup(0);
                }
            }
        }

        @Override
        public void onDatastoreDownloadingDataItemCompleted(String id) {
        }

        @Override
        public void onDatastoreDownloadingDataItemFailed(String id, int errorCode) {
            lastDownloadingProgressUpdateTime = System.currentTimeMillis();
            expandLv.collapseGroup(0);
            expandLv.expandGroup(0);
        }

        @Override
        public void onDatastoreInstallDataItemBegan(String id) {
        }

        @Override
        public void onDatastoreInstallDataItemProgressUpdated(String id, float percent) {
            if (isRefrePercent) {
                //0.5s刷新一次
                if (System.currentTimeMillis() - lastDownloadingProgressUpdateTime > 500) {
                    lastDownloadingProgressUpdateTime = System.currentTimeMillis();
                    expandLv.collapseGroup(0);
                    expandLv.expandGroup(0);
                }
            }
        }

        @Override
        public void onDatastoreInstallDataItemFinished(String id) {
        }

        @Override
        public void onDatastoreInstallDataItemFailed(String id, int errorCode) {
            refreshDataList();
        }

        @Override
        public void onDataItemStateChanged(String id) {
            if (mDataStoreItems == null) {
                //上次有等待安装的，安装完成后，首次回调此函数
                return;
            }
            refreshDataList();
        }
    };
}
